<?php

class Fetcher {
	private $curlOptions = array();

	function __construct() {
		$cookies = 'cookies.txt';
		// Fix temp folder for cookies on UNIX
		if (!stristr(PHP_OS, 'WIN')) {
			$cookies = "/tmp/$cookies";
		}

		$this->curlOptions = array(
			CURLOPT_SSL_VERIFYPEER => false, // Needed for https://
			CURLOPT_USERAGENT      => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6',
			CURLOPT_HEADER         => false, // Add response headers to return, for testing
			CURLOPT_FOLLOWLOCATION => true, // Follow if the site redirects
			CURLOPT_AUTOREFERER    => true,
			CURLOPT_RETURNTRANSFER => true, // Add html to return
			CURLOPT_FAILONERROR    => true,
			CURLOPT_COOKIEJAR      => $cookies, // Create cookies
			CURLOPT_COOKIEFILE     => $cookies,
		);
	}

	function fetch($url) {
		$ch = curl_init();

		$curlOptions = $this->curlOptions;
		$curlOptions[CURLOPT_URL] = $url;
		curl_setopt_array($ch, $curlOptions);

		$result = curl_exec($ch);

		if (!$result) {
			echo "<br /><b>Ett fel uppstod när sidan skulle hämtas</b>";
			echo "<br />cURL error number:" .curl_errno($ch);
			echo "<br />cURL error:" . curl_error($ch);
			exit;
		}

		// Close curl session
		curl_close($ch);

		return $result;
	}
}

